package com.hzh.cusviewdemo.Music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.hzh.cusviewdemo.Activity.MusicActivity;
import com.hzh.cusviewdemo.Bean.CheckKeyData;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Util.DialogUtils;
import com.hzh.cusviewdemo.Util.RSAUtil;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 倒计时服务
 */
public class TimeOverService extends Service implements MusicPresenter {

    private Timer mTimer; // 倒计时计时器，用来处理倒计时退出
    private Date date = new Date(); // 一直在记录的当前时间
    private MediaPlayer mediaPlayer;  // 语音提示

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 获取到需要退出的时间
        String quitTime = intent.getStringExtra("INTENT_QUIT_TIME");
        // 收到到期时间之后，开始倒计时退出机制
        final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 初始化计时器
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 更新当前时间到date
                date.setTime(System.currentTimeMillis());
                if (simpleFormat.format(date).equals(quitTime)) {
                    // 到了时间，整个APP直接退出
                    // 停止计时器
                    mTimer.cancel();
                    // 发送倒计时时间到期到主页通知
                    Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);    //接收广播为MusicUpdateMain
                    musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_KEY_TIME);
                    musicIntent.putExtra("KEY_EXPIRE_TIME", "0");
                    sendBroadcast(musicIntent);
                    // 发送歌曲暂停通知
                    pauseMusic();
                    // System.exit(0); 直接退出APP的代码，体验不好 所以这里注释了
                    DialogUtils.showErrorToast("时间结束，请重新输入秘钥开始使用~");
                    showCheckDialog();
                }
            }
        }, 0, 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 全局暂停音乐
     */
    private void pauseMusic() {
        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PAUSE);
        sendBroadcast(intent);
        // 人工语音播报秘钥已到期
        playKeyExpireAudio();
    }

    private void playKeyExpireAudio() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(this, R.raw.audio_key_expire_tip);
            mediaPlayer.start();
        } else {
            mediaPlayer.start();
        }
    }

    private void showCheckDialog() {
        DialogUtils.showCheckKeyDialog(new DialogUtils.CheckKeyCallBack() {
            @Override
            public void onCheck(CustomDialog dialog, String key) {
                checkKey(key, new OnCheckKeyListener() {
                    @Override
                    public void onCheckOk(String result) {
                        // 对result 解密
                        checkOk(key, result, dialog);
                    }

                    @Override
                    public void onCheckFail(String msg) {
                        DialogUtils.showErrorToast(msg);
                    }
                });
            }

            @Override
            public void onQuit(CustomDialog dialog) {
                AppUtils.exitApp();
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止计时器
        mTimer.cancel();
        // 语音播报处理
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        // DialogUtils.showErrorToast("程序异常，请重新输入秘钥开始使用~");
    }

    private void checkOk(String key, String result, CustomDialog dialog) {
        WaitDialog.show("");
        new Thread(() -> {
            String decryptData = RSAUtil.decrypt(result);
            CheckKeyData checkKeyData = JSONObject.parseObject(decryptData, CheckKeyData.class);
            if (checkKeyData == null) {
                DialogUtils.showErrorToast("非法操作0x11");
                WaitDialog.dismiss();
                return;
            }
            if (!checkKeyData.getKey().equals(key)) {
                DialogUtils.showErrorToast("非法操作0x22");
                WaitDialog.dismiss();
                return;
            }
            if (!checkKeyData.getDeviceCode().equals(DialogUtils.getDeviceCode())) {
                DialogUtils.showErrorToast("非法操作0x33");
                WaitDialog.dismiss();
                return;
            }
            Date expireDate = com.blankj.utilcode.util.TimeUtils.string2Date(checkKeyData.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
            Date nowDate = new Date();
            if (expireDate.before(nowDate)) {
                DialogUtils.showErrorToast("已过期，请重新去获取秘钥~");
                WaitDialog.dismiss();
                return;
            }
            // 卡密正常处理
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            MyMusicUtil.setShared(Constant.SAVE_USER_KEY, checkKeyData.getKey());
            // 发送倒计时时间到期到主页通知
            Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);    //接收广播为MusicUpdateMain
            musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_KEY_TIME);
            musicIntent.putExtra("KEY_EXPIRE_TIME", checkKeyData.getExpireTime());
            sendBroadcast(musicIntent);
            DialogUtils.showSuccessToast("校验成功\n到期时间：" + checkKeyData.getExpireTime());
            // 开启倒计时服务
            final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mTimer = null;
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 更新当前时间到date
                    date.setTime(System.currentTimeMillis());
                    if (simpleFormat.format(date).equals(checkKeyData.getExpireTime())) {
                        // 停止计时器
                        mTimer.cancel();
                        // 发送歌曲暂停通知
                        pauseMusic();
                        Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);    //接收广播为MusicUpdateMain
                        musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_KEY_TIME);
                        musicIntent.putExtra("KEY_EXPIRE_TIME", "0");
                        sendBroadcast(musicIntent);
                        // System.exit(0); 直接退出APP的代码，体验不好 所以这里注释了
                        DialogUtils.showErrorToast("时间结束，请重新输入秘钥开始使用~");
                        showCheckDialog();
                    }
                }
            }, 0, 1000);
            // 消失对应加载
            dialog.dismiss();
            WaitDialog.dismiss();
        }).start();
    }
}
